﻿using System;
using System.Web;
using iSun.BLL.Base;
using iSun.Web.UI.Controls;
using iSun.CRM.Library;
using iSun.Common;
using System.Collections;
using System.Collections.Generic;
using iSun.CRM.Bussiness;
using iSun.DAL.DBExtend;
using iSun.DBModule;
using System.Data.SqlClient;
using System.Data;
using iSun.TR.Bussiness;
using iSun.TR.Library;
using iSun.WebApp.CrmWorkFlowService;
using iSun.BLL;
using iSun.EHR.Library;
using iSun.SYS.Bussiness.Message;
using iSun.SYS.Library;
namespace iSun.WebApp.AjaxData
{
    public partial class CustomOperating : BasePage
    {
        BTCrmCustomer bll = new BTCrmCustomer();
        protected void Page_Load(object sender, EventArgs e)
        {
            string strAction = this.GetStringFromQueryString("action", "");
            string strEntity = this.GetStringFromQueryString("entity", "E_Menu");
            string flag = this.GetStringFromQueryString("flag", "");
            string strType = this.GetStringFromQueryString("type", "");
            string strJson = "";
            if (flag == "1")
            {
                string Forms = ZXContext.Request.Form[0].ToString();
                strJson = Forms;
            }
            else
            {
                strJson = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");
            }
            if (strType == "1" && strEntity == "CrmCustomerAttach")
            {
                string id = this.GetStringFromQueryString("id", "");
                IList<V_CrmCustomerAttach> listAttach = bll.GetAllCrmCustomerAttachInfo(new Guid(id));
                if (listAttach != null && listAttach.Count > 0)
                {
                    IList<BaseEntity> _listAttach = new List<BaseEntity>();
                    foreach (var _e in listAttach)
                    {
                        _listAttach.Add(_e);
                    }
                    string strAttach = "[" + _listAttach.ToJSON().Replace("\n", "").Replace("\r", "").Replace("@@", "") + "]";
                    //ZX.Common.Globals.ObjectToJSON(listAttach);
                    HttpContext.Current.Response.Write(strAttach);
                }
                else
                {
                    IList<V_CrmCustomerAttach> listAttachInfo = bll.GetAllCrmCustomerInfoAttachInfo(new Guid(id));
                    if (listAttachInfo != null && listAttachInfo.Count > 0)
                    {
                        IList<BaseEntity> _listAttachInfo = new List<BaseEntity>();
                        foreach (var _e in listAttachInfo)
                        {
                            _listAttachInfo.Add(_e);
                        }
                        string strAttach = "[" + _listAttachInfo.ToJSON().Replace("\n", "").Replace("\r", "").Replace("@@", "") + "]";
                        HttpContext.Current.Response.Write(strAttach);
                    }
                }
                return;
            }
            switch (strAction)
            {
                case "delete":
                    RunDelete(strEntity, strJson);
                    break;
                case "procedure":
                    RunProcedure(strEntity, strJson, strAction);
                    break;
                case "check":
                    RunCheck(strEntity, strJson);
                    break;
                case "insert":
                    InsertIntoInfo(strEntity, strJson);
                    break;
                case "lenovo":
                    LoadCustomerName(strJson);
                    break;
                case "update":
                    RunUpdate(strEntity, strJson);
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 自定义删除方法
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void RunDelete(string strEntity, string strJson)
        {
            switch (strEntity)
            {
                case "CrmUserMove":
                    CrmUserMoveDelete(strJson);
                    break;
                case "CrmLinkMan":
                    DeleteCrmLinkMan(strJson);
                    break;
                case "CrmActivity":
                    DeleteCrmActivity(strJson);
                    break;
                case "CrmCustomerAttach":
                    DeleteCrmCustomerAttach(strJson);
                    break;
                case "CrmCustomer":
                case "CrmCustomerInfo":
                    SetCrmCustomerIsValue(strEntity, strJson);
                    break;
                default:
                    break;
            }
        }
        private void CrmUserMoveDelete(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                string strSql = string.Format("update CrmUserMove set IsValue='0' where ID='{0}'", strJson);
                int iResult = bll.RunSqlCommand(strSql);
                if (iResult  > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        private void DeleteCrmLinkMan(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                string strSql = string.Format("delete CrmLinkMan where ID='{0}'", strJson);
                int iResult = bll.RunSqlCommand(strSql);
                if (iResult > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        private void DeleteCrmActivity(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                string strSql = string.Format("delete CrmActivity where ID='{0}'", strJson);
                int iResult = bll.RunSqlCommand(strSql);
                if (iResult > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        private void DeleteCrmCustomerAttach(string strJson)
        {
            strJson = this.GetStringFromQueryString("aid", "");
            string strCustomerId = this.GetStringFromQueryString("id", "");
            string ListId = this.GetStringFromQueryString("listId", "");
            string strListId = "";
            if (ListId != "")
            {
                strListId = ListId.Substring(0, ListId.Length - 1);
            }
            try
            {
                string strSql = string.Format("Exec sp_DelCrmCustomerAttach '{0}','{1}','{2}'",
                                            strJson, strCustomerId, strListId);
                int iResult = bll.RunSqlCommand(strSql);
                if (iResult > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 停用客户
        /// </summary>
        /// <param name="strJson"></param>
        private void SetCrmCustomerIsValue(string strEntity, string strJson)
        {
            string strSql = "";
            BaseBussnies blls = new BaseBussnies();
            strJson = this.GetStringFromQueryString("id", "");
            string type = this.GetStringFromQueryString("type", "");
            try
            {
                if (strEntity == "CrmCustomer")  //CrmCustomer停用客户
                {
                    if (bll.CheckCustomerIsPrevateState(new Guid(strJson)))
                    {
                        strSql = string.Format("update CrmCustomer set IsValue='{0}' where ID='{1}'", type, strJson);
                    }
                    else
                    {
                        //该客户已被处理，不是公海客户，请及时刷新数据!
                        HttpContext.Current.Response.Write("2");
                        return;
                    }
                }
                else if (strEntity == "CrmCustomerInfo")  //CrmCustomerInfo停用客户
                {
                    strSql = string.Format("update CrmCustomerInfo set IsValue='{0}' where ID='{1}'", type, strJson);
                }
                int iResult = blls.RunSqlCommand(strSql);
                if (iResult > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }


        /// <summary>
        /// 自定义修改方法
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void RunUpdate(string strEntity, string strJson)
        {
            switch (strEntity)
            {
                case "CrmCustomer":
                    ModifyCrmCustomerAddUserId(strJson);
                    break;
                case "CrmCustomerOrderField":
                    ModifyCrmCustomerOrder(strJson);
                    break;
                case "CrmPay":
                    ModifyCrmCustomerPay(strJson);
                    break;
                case "CrmCustomerInfo":
                    ModifyCrmCustomerDistribution(strJson);
                    break;
                case "CrmCustomerOrder":
                    ModifyCustomerOrderCheckState(strJson);
                    break;
                case "CrmCustomerOrderF":
                case "CrmCustomerOrderS":
                    ModifyCustomerOrderInfo(strEntity, strJson);
                    break;
                case "CrmCustomerReturn":
                    UpdateCrmCustomerReturn(strJson);
                    break;
                case "CrmDeliverMajor":
                    UpdateCrmDeliverMajor(strJson);
                    break;
                case "CrmDeliverMajorProject":
                    UpdateCrmDeliverMajorProject(strJson);
                    break;
                case "CrmDeliverScb":
                    UpdateCrmDeliverScb(strJson);
                    break;
                case "CrmDeliverSsr":
                    UpdateCrmDeliverSsr(strJson);
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 修改信息专员
        /// </summary>
        /// <param name="strJson"></param>
        private void ModifyCrmCustomerAddUserId(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");  //客户ID
            try
            {
                if (bll.CheckCustomerIsPrevateState(new Guid(strJson)))
                {
                    string strId = this.GetStringFromQueryString("userid", ""); //专员ID
                    string strSql = string.Format("Exec sp_UpdateCrmCustomerUserId '{0}','{1}','{2}'", strJson, strId, this.UserId);
                    int iResult = bll.RunSqlCommand(strSql);
                    if (iResult > 0)
                    {
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("修改失败!");
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("该客户已被处理，不是公海客户，请及时刷新数据!");
                    return;
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("修改失败!");
            }
        }
        /// <summary>
        /// 订单变更
        /// </summary>
        /// <param name="strJson"></param>
        private void ModifyCrmCustomerOrder(string strJson)
        {
            strJson = this.GetStringFromQueryString("oid", "");//订单ID
            string strCustomerId = this.GetStringFromQueryString("cid","");//客户ID
            string strName = this.GetStringFromQueryString("name","");//订单名称
            string strOrderStateId = this.GetStringFromQueryString("sid", "");//订单状态ID
            try
            {
                string strSql = string.Format("Exec sp_EditCrmCustomerOrder '{0}','{1}','{2}','{3}','{4}','{5}'",
                                        strJson, strCustomerId, strOrderStateId, this.UserId, DateTime.Now, strName);
                int iResult = bll.RunSqlCommand(strSql);
                if (iResult > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("修改失败!");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("修改失败!");
            }
        }
        /// <summary>
        /// 修改订单信息--新建状态下修改
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void ModifyCustomerOrderInfo(string strEntity, string strJson)
        {
            int iResult = 0;
            IDataParameter[] _Parameters = new IDataParameter[] { };
            DbSql db = new DbSql();
            try
            {
                CrmCustomerOrder instance = (CrmCustomerOrder)Globals.JSonToObject<CrmCustomerOrder>(strJson);
                Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);

                SqlParameter ID = new SqlParameter("@ID", SqlDbType.UniqueIdentifier, 50);
                ID.Direction = ParameterDirection.Input;
                ID.Value = instance.ID;
                SqlParameter Code = new SqlParameter("@Code", SqlDbType.Char, 50);
                Code.Direction = ParameterDirection.Input;
                Code.Value = instance.Code;
                SqlParameter CustomerId = new SqlParameter("@CustomerId", SqlDbType.UniqueIdentifier, 50);
                CustomerId.Direction = ParameterDirection.Input;
                CustomerId.Value = instance.CustomerId;
                SqlParameter DeptId = new SqlParameter("@DeptId", SqlDbType.UniqueIdentifier, 50);
                DeptId.Direction = ParameterDirection.Input;
                DeptId.Value = instance.DeptId;
                SqlParameter Date = new SqlParameter("@Date", SqlDbType.DateTime, 50);
                Date.Direction = ParameterDirection.Input;
                Date.Value = instance.Date;
                SqlParameter TypeID = new SqlParameter("@TypeID", SqlDbType.UniqueIdentifier, 50);
                TypeID.Direction = ParameterDirection.Input;
                TypeID.Value = instance.TypeID;
                SqlParameter ValutaID = new SqlParameter("@ValutaID", SqlDbType.UniqueIdentifier, 50);
                ValutaID.Direction = ParameterDirection.Input;
                ValutaID.Value = instance.ValutaID;
                SqlParameter PillID = new SqlParameter("@PillID", SqlDbType.UniqueIdentifier, 50);
                PillID.Direction = ParameterDirection.Input;
                PillID.Value = instance.PillID;
                SqlParameter CourseLoyoutID = new SqlParameter("@CourseLoyoutID", SqlDbType.UniqueIdentifier, 50);
                CourseLoyoutID.Direction = ParameterDirection.Input;
                CourseLoyoutID.Value = instance.CourseLoyoutID;
                SqlParameter PaymentId = new SqlParameter("@PaymentId", SqlDbType.UniqueIdentifier, 50);
                PaymentId.Direction = ParameterDirection.Input;
                PaymentId.Value = instance.PaymentId;
                SqlParameter Explain = new SqlParameter("@Explain", SqlDbType.NVarChar, 1000);
                Explain.Direction = ParameterDirection.Input;
                Explain.Value = instance.Explain;
                SqlParameter AddUser = new SqlParameter("@AddUser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = instance.AddUser;
                SqlParameter AddTime = new SqlParameter("@AddTime", SqlDbType.DateTime, 50);
                AddTime.Direction = ParameterDirection.Input;
                AddTime.Value = instance.AddTime;
                SqlParameter TotalMoney = new SqlParameter("@TotalMoney", SqlDbType.Decimal, 20);
                TotalMoney.Direction = ParameterDirection.Input;
                TotalMoney.Value = instance.TotalMoney;
                SqlParameter StateID = new SqlParameter("@StateID", SqlDbType.UniqueIdentifier, 50);
                StateID.Direction = ParameterDirection.Input;
                StateID.Value = instance.StateID;

                SqlParameter ProduectList = new SqlParameter("@ProduectList", SqlDbType.NVarChar, 4000);
                ProduectList.Direction = ParameterDirection.Input;
                ProduectList.Value = instance.ProduectList;
                SqlParameter CustomerZjList = new SqlParameter("@CustomerZjList", SqlDbType.NVarChar, 4000);
                CustomerZjList.Direction = ParameterDirection.Input;
                CustomerZjList.Value = instance.CustomerZjList;
                SqlParameter CustomerServerList = new SqlParameter("@CustomerServerList", SqlDbType.NVarChar, 4000);
                CustomerServerList.Direction = ParameterDirection.Input;
                CustomerServerList.Value = instance.CustomerServerList;

                SqlParameter TeacherId = new SqlParameter("@TeacherId", SqlDbType.UniqueIdentifier, 50);
                TeacherId.Direction = ParameterDirection.Input;
                TeacherId.Value = instance.TeacherId;
                SqlParameter TeacherTime = new SqlParameter("@TeacherTime", SqlDbType.DateTime, 50);
                TeacherTime.Direction = ParameterDirection.Input;
                TeacherTime.Value = instance.TeacherTime;
                SqlParameter TeacherAddress = new SqlParameter("@TeacherAddress", SqlDbType.NVarChar, 40);
                TeacherAddress.Direction = ParameterDirection.Input;
                TeacherAddress.Value = instance.TeacherAddress;
                SqlParameter TeacherType = new SqlParameter("@TeacherType", SqlDbType.NVarChar, 50);
                TeacherType.Direction = ParameterDirection.Input;
                TeacherType.Value = instance.TeacherType;

                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;

                if (strEntity == "CrmCustomerOrderF")  //约场订单
                {
                    SqlParameter OrderType = new SqlParameter("@OrderType", SqlDbType.Int, 1);
                    OrderType.Direction = ParameterDirection.Input;
                    OrderType.Value = 0;
                    _Parameters = new IDataParameter[] { ID,Code, CustomerId, DeptId, Date, TypeID, ValutaID, 
                        PillID, CourseLoyoutID, PaymentId, Explain, AddUser, AddTime, TotalMoney, StateID, OrderType,
                        ProduectList,CustomerZjList,CustomerServerList,TeacherId,TeacherTime,TeacherAddress,TeacherType, ReturnValue};
                }
                else if (strEntity == "CrmCustomerOrderS")  //其它类型订单
                {
                    SqlParameter OrderType = new SqlParameter("@OrderType", SqlDbType.Int, 1);
                    OrderType.Direction = ParameterDirection.Input;
                    OrderType.Value = 1;
                    _Parameters = new IDataParameter[] { ID,Code, CustomerId, DeptId, Date, TypeID, ValutaID, 
                        PillID, CourseLoyoutID, PaymentId, Explain, AddUser, AddTime, TotalMoney, StateID, OrderType,
                        ProduectList,CustomerZjList,CustomerServerList,TeacherId,TeacherTime,TeacherAddress,TeacherType, ReturnValue};
                }
                string strSql = db.RunProcedureReturnString("sp_UpdateCrmCustomerOrder", _Parameters, out iResult);
                if (strSql == "1")
                {
                    HttpContext.Current.Response.Write("1");
                }
                else if (strSql == "2") 
                {
                    HttpContext.Current.Response.Write("该讲师在当前时间段已安排讲场!");
                }
                else
                {
                    HttpContext.Current.Response.Write("保存数据失败!");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("保存数据失败!");
            }
        }
        /// <summary>
        /// 缴款单变更
        /// </summary>
        /// <param name="strJson"></param>
        private void ModifyCrmCustomerPay(string strJson)
        {
            try
            {
                int iResult = 0;
                IDataParameter[] _Parameters = new IDataParameter[] { };
                DbSql db = new DbSql();
                CrmPay instance = (CrmPay)Globals.JSonToObject<CrmPay>(strJson);
                SqlParameter ID = new SqlParameter("@ID", SqlDbType.UniqueIdentifier, 50);
                ID.Direction = ParameterDirection.Input;
                ID.Value = instance.ID;
                SqlParameter DeptId = new SqlParameter("@DeptId", SqlDbType.UniqueIdentifier, 50);
                DeptId.Direction = ParameterDirection.Input;
                DeptId.Value = instance.DeptId;
                
                SqlParameter ValutaID = new SqlParameter("@ValutaID", SqlDbType.UniqueIdentifier, 50);
                ValutaID.Direction = ParameterDirection.Input;
                ValutaID.Value = instance.ValutaID;
                SqlParameter PillID = new SqlParameter("@PillID", SqlDbType.UniqueIdentifier, 50);
                PillID.Direction = ParameterDirection.Input;
                PillID.Value = instance.PillID;
                SqlParameter InvoiceNum = new SqlParameter("@InvoiceNum", SqlDbType.NVarChar, 50);
                InvoiceNum.Direction = ParameterDirection.Input;
                InvoiceNum.Value = instance.@InvoiceNum;
                SqlParameter Explain = new SqlParameter("@Explain", SqlDbType.NVarChar, 1000);
                Explain.Direction = ParameterDirection.Input;
                Explain.Value = instance.Explain;

                SqlParameter StateID = new SqlParameter("@State", SqlDbType.UniqueIdentifier, 50);
                StateID.Direction = ParameterDirection.Input;
                StateID.Value = instance.State;

                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;

                _Parameters = new IDataParameter[] {ID,ValutaID, DeptId,PillID,InvoiceNum, StateID,Explain,  ReturnValue};

                string strSql = db.RunProcedureReturnString("sp_EditCrmCustomerPay", _Parameters, out iResult);
                if (strSql == "1")
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("保存数据失败!");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("修改失败!");
            }
        }
        /// <summary>
        /// 客户分配
        /// </summary>
        /// <param name="strJson"></param>
        private void ModifyCrmCustomerDistribution(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");  //客户ID
            string strUserId = this.GetStringFromQueryString("uid", "");  //分配的用户ID
            try
            {
                string strSql = string.Format("Exec sp_AddCrmCustomerDistribution '{0}','{1}','{2}'",
                                    strJson, strUserId, this.UserId);
                int iResult = bll.RunSqlCommand(strSql);
                if (iResult > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 订单审核
        /// </summary>
        /// <param name="strJson"></param>
        private void ModifyCustomerOrderCheckState(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");  //订单ID
            string strCheckId = this.UserId.ToString();
            try
            {
                BTCrmCrustomerOrder bllOrder = new BTCrmCrustomerOrder();
                V_CrmCustomerOrder Orders = bllOrder.GetAllCrmCustomerOrder(new Guid(strJson));
                if (Orders.StateID.ToString() == "319FDCFA-3948-495B-88B0-1EAB7DC9F138")
                {
                    HttpContext.Current.Response.Write("您当前的订单处于 签核中 状态，无须审核!");
                    return;
                }
                else if (Orders.StateID.ToString() == "af73673f-9fec-4d14-acfd-b0fce08d6ffa")
                {
                    HttpContext.Current.Response.Write("您当前的订单处于 待交付 状态，无须审核!");
                    return;
                }
                else if (Orders.StateID.ToString() == "eda4faa9-8544-494c-bf1c-02662e1078a6")
                {
                    HttpContext.Current.Response.Write("您当前的订单处于 交付中 状态，无须审核!");
                    return;
                }
                else if (Orders.StateID.ToString() == "bddcaf31-98d4-423a-9275-9288f85e2847")
                {
                    HttpContext.Current.Response.Write("您当前的订单处于 结案 状态，无须审核!");
                    return;
                }
                else if (Orders.StateID.ToString() == "c2af1c1f-6937-40ee-8d40-2e6203e34119")
                {
                    HttpContext.Current.Response.Write("您当前的订单处于 报废 状态，无须审核!");
                    return;
                }
                else
                {
                    BaseBussnies blls = new BaseBussnies();
                    string strSql = string.Format("update CrmCustomerOrder set StateID='{0}', CheckID='{1}',CheckTime='{2}' where ID='{3}'",
                                                    "af73673f-9fec-4d14-acfd-b0fce08d6ffa", strCheckId, DateTime.Now.ToString(), strJson);
                    int iResult = blls.RunSqlCommand(strSql);
                    if (iResult > 0)
                    {
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("审核失败!");
                    }
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("审核失败!");
            }
        }
        /// <summary>
        /// 客户退回时修改退回列表信息
        /// </summary>
        /// <param name="strJson"></param>
        private void UpdateCrmCustomerReturn(string strJson)
        {
            try
            {
                strJson = this.GetStringFromQueryString("id", "");  //退回列表ID
                BaseBussnies bll = new BaseBussnies();
                string strSql = string.Format("update CrmCustomerReturn set CustomerState={0},ModifyUser='{1}',ModifyTime='{2}' where ID='{3}'",
                                               1, this.UserId, DateTime.Now, strJson);
                int iResult = bll.RunSqlCommand(strSql);
                if (iResult > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 大课-更新产品规划
        /// </summary>
        /// <param name="strJson"></param>
        private void UpdateCrmDeliverMajor(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");//大课ID
            string ProductLayoutId = this.GetStringFromQueryString("pid", ""); //产品规划ID
            string strOperatorInstanceId = this.GetStringFromQueryString("oid",""); //流程操作ID
            string strWorkTaskInsId = this.GetStringFromQueryString("tid",""); //流程任务ID
            try
            {
                string strSql = string.Format("update CrmDeliverMajor set ProductLayoutID='" + ProductLayoutId + "' where ID='" + strJson + "'");
                int iResult = bll.RunSqlCommand(strSql);

                if (iResult > 0)
                {
                    CrmWorkFlowService.WorkFlowServiceClient workFlowServiceClient = new WorkFlowServiceClient();
                    string msg1 = workFlowServiceClient.Run(this.User.LoginName, strOperatorInstanceId, "提交");
                    HttpContext.Current.Response.Write("1");
                }

                /*if (iResult > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }*/
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 项目-更新实施团队
        /// </summary>
        /// <param name="strJson"></param>
        private void UpdateCrmDeliverSsr(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");//大课ID
            string DateSum = this.GetStringFromQueryString("DateSum", ""); //项目天数
            string EndDate = this.GetStringFromQueryString("EndDate", "");//结束日期
            string SsExplain = this.GetStringFromQueryString("SsExplain", "");//备注
            string SsUser = this.GetStringFromQueryString("SsUser", "");//添加用户
            string SsDate = this.GetStringFromQueryString("SsDate", "");
            string strOperatorInstanceId = this.GetStringFromQueryString("oid", ""); //流程操作ID
            string strWorkTaskInsId = this.GetStringFromQueryString("tid", ""); //流程任务ID
            try
            {
                string strSql = string.Format("update CrmDeliverMajorProject set DateSum=" + DateSum + " ,EndDate='" + EndDate + "', SsExplain='" + SsExplain + "',SsUser='" + SsUser + "',SsDate='" + SsDate + "' where ID='" + strJson + "'");
                int iResult = bll.RunSqlCommand(strSql);

                if (iResult > 0)
                {
                    CrmWorkFlowService.WorkFlowServiceClient workFlowServiceClient = new WorkFlowServiceClient();
                    string msg1 = workFlowServiceClient.Run(this.User.LoginName, strOperatorInstanceId, "提交");
                    HttpContext.Current.Response.Write("1");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 项目-更新
        /// </summary>
        /// <param name="strJson"></param>
        private void UpdateCrmDeliverMajorProject(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");//大课ID
            string PM = this.GetStringFromQueryString("PM", ""); //项目经理ID
            string BeginDate = this.GetStringFromQueryString("BeginDate", "");//启动日期
            string PMemember = this.GetStringFromQueryString("PMemember", "");//项目成员
            string PExplain = this.GetStringFromQueryString("PExplain", "");//备注
            string ProjectUser = this.GetStringFromQueryString("ProjectUser", "");//添加用户
            string ProjectDate = this.GetStringFromQueryString("ProjectDate", "");
            string strOperatorInstanceId = this.GetStringFromQueryString("oid", ""); //流程操作ID
            string strWorkTaskInsId = this.GetStringFromQueryString("tid", ""); //流程任务ID
            try
            {
                string strSql = string.Format("update CrmDeliverMajorProject set PM='" + PM + "' ,BeginDate='" + BeginDate + "',PMemember='" + PMemember + "', PExplain='" + PExplain + "',ProjectUser='" + ProjectUser + "',ProjectDate='" + ProjectDate + "' where ID='" + strJson + "'");
                int iResult = bll.RunSqlCommand(strSql);

                if (iResult > 0)
                {
                    CrmWorkFlowService.WorkFlowServiceClient workFlowServiceClient = new WorkFlowServiceClient();
                    string msg1 = workFlowServiceClient.Run(this.User.LoginName, strOperatorInstanceId, "提交");
                    HttpContext.Current.Response.Write("1");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 项目-更新市场部
        /// </summary>
        /// <param name="strJson"></param>
        private void UpdateCrmDeliverScb(string strJson)
        {
            strJson = this.GetStringFromQueryString("id", "");//大课ID
            string SucceedDegree = this.GetStringFromQueryString("SucceedDegree", ""); //项目经理ID
            string WellDegree = this.GetStringFromQueryString("WellDegree", "");//启动日期
            string PMemember = this.GetStringFromQueryString("PMemember", "");//项目成员
            string Explain = this.GetStringFromQueryString("Explain", "");//备注
            string DegreeUser = this.GetStringFromQueryString("DegreeUser", "");//添加用户
            string DegreeDate = this.GetStringFromQueryString("DegreeDate", "");
            string strOperatorInstanceId = this.GetStringFromQueryString("oid", ""); //流程操作ID
            string strWorkTaskInsId = this.GetStringFromQueryString("tid", ""); //流程任务ID
            try
            {
                string strSql = string.Format("update CrmDeliverMajorProject set SucceedDegree=" + SucceedDegree + " ,WellDegree=" + WellDegree + ", Explain='" + Explain + "',DegreeUser='" + DegreeUser + "',DegreeDate='" + DegreeDate + "' where ID='" + strJson + "'");
                int iResult = bll.RunSqlCommand(strSql);

                if (iResult > 0)
                {
                    CrmWorkFlowService.WorkFlowServiceClient workFlowServiceClient = new WorkFlowServiceClient();
                    string msg1 = workFlowServiceClient.Run(this.User.LoginName, strOperatorInstanceId, "提交");
                    HttpContext.Current.Response.Write("1");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }


        /// <summary>
        /// 自定义保存方法，执行存储过程
        /// </summary>
        /// <param name="strEntity">实体</param>
        /// <param name="strJson">JSON数据</param>
        /// <param name="strAction">动作</param>
        private void RunProcedure(string strEntity, string strJson, string strAction)
        {
            BaseBussnies blls = new BaseBussnies();
            BTCrmCustomer bt = new BTCrmCustomer();
            CrmCustomerReturn instanceReturn = new CrmCustomerReturn();
            try
            {
                string strSql = "";
                if (strAction == "procedure")
                {
                    #region ------ CrmUserMove(员工异动) ------
                    if (strEntity == "CrmUserMove")
                    {
                        CrmUserMove instance = Globals.JSonToObject<CrmUserMove>(strJson);
                        Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                        Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);
                        //数据验证
                        string strMsg = instance.CheckData();
                        if (strMsg != "")
                        {
                            HttpContext.Current.Response.Write(strMsg);
                            return;
                        }
                        strSql = string.Format("Exec sp_CrmUserMove '{0}','{1}','{2}','{3}'",
                                            instance.MoverUserID, instance.MoveDate, instance.Explain, instance.AddUser);
                    }
                    #endregion
                    #region ------ CrmLinkMan(添加联系人)  ------
                    else if (strEntity == "CrmLinkMan")
                    {
                        var list = (List<CrmLinkMan>)Globals.JSonToObject<List<CrmLinkMan>>(strJson);
                        foreach (var v in list)
                        {
                            Globals.SetPropertyValue(v, "AddUser", this.UserId);
                            Globals.SetPropertyValue(v, "AddTime", System.DateTime.Now);
                            string strSqls = string.Format("Exec sp_AddCrmLinkMan '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}'",
                                                v.ID, iSun.BLL.IDMaker.GetSequenceStr("CUS002"), v.Caption, v.CustomId, v.TypeID, v.Sex, v.Position,
                                                v.DeptName, v.MobileTel, v.Email, v.AddUser, v.AddTime);
                            int iResults = bll.RunSqlCommand(strSqls);
                            if (iResults > 0)
                            {
                            }
                            else
                            {
                                HttpContext.Current.Response.Write("0");
                                return;
                            }
                        }
                        HttpContext.Current.Response.Write("1");
                        return;
                    }
                    #endregion
                    #region ------ CrmActivity(添加联系记录) ------
                    else if (strEntity == "CrmActivity")
                    {
                        var list = (List<CrmActivity>)Globals.JSonToObject<List<CrmActivity>>(strJson);
                        foreach (var v in list)
                        {
                            Globals.SetPropertyValue(v, "AddUser", this.UserId);
                            Globals.SetPropertyValue(v, "AddTime", System.DateTime.Now);
                            if(v.PlanStartDate.ToString() == "0001-1-1 0:00:00")
                            {
                                v.PlanStartDate = DateTime.Now;
                            }
                            if (v.PlanEndDate.ToString() == "0001-1-1 0:00:00")
                            {
                                v.PlanEndDate = DateTime.Now;
                            }
                            string strSqls = string.Format("Exec sp_AddCrmActivity '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}'",
                                                v.ID, iSun.BLL.IDMaker.GetSequenceStr("CUS003"),v.Caption, v.CustomId, v.TypeId, v.LinkManID, v.PlanStartDate,
                                                v.PlanEndDate, v.Contents, v.Explain, v.AddUser,
                                                v.AddTime, v.AddUser, v.AddTime);
                            int iResults = bll.RunSqlCommand(strSqls);
                            if (iResults > 0)
                            {
                            }
                            else
                            {
                                HttpContext.Current.Response.Write("0");
                                return;
                            }
                        }
                        HttpContext.Current.Response.Write("1");
                        return;
                    }
                    #endregion
                    #region ------ CrmActivityCall(添加拜访记录) ------
                    else if (strEntity == "CrmActivityCall")
                    {
                        var list = (List<CrmActivity>)Globals.JSonToObject<List<CrmActivity>>(strJson);
                        foreach (var v in list)
                        {
                            Globals.SetPropertyValue(v, "AddUser", this.UserId);
                            Globals.SetPropertyValue(v, "AddTime", System.DateTime.Now);
                            if (v.PlanStartDate.ToString() == "0001-1-1 0:00:00")
                            {
                                v.PlanStartDate = DateTime.Now;
                            }
                            if (v.PlanEndDate.ToString() == "0001-1-1 0:00:00")
                            {
                                v.PlanEndDate = DateTime.Now;
                            }
                            string strSqls = string.Format("Exec sp_AddCrmActivityCall '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}'",
                                                v.ID, iSun.BLL.IDMaker.GetSequenceStr("CUS003"), v.Suject, v.CustomId, v.TypeId, v.LinkManID, v.PlanStartDate,
                                                v.PlanEndDate,v.AnticipeResult, v.Contents,v.Result, v.Explain, v.AddUser,
                                                v.AddTime, v.AddUser, v.AddTime);
                            int iResults = bll.RunSqlCommand(strSqls);
                            if (iResults > 0)
                            {
                            }
                            else
                            {
                                HttpContext.Current.Response.Write("0");
                                return;
                            }
                        }
                        HttpContext.Current.Response.Write("1");
                        return;
                    }
                    #endregion
                    #region --- CrmPrivateCustom(公海转私海) ----
                    else if (strEntity == "CrmPrivateCustom")
                    {
                        strJson = this.GetStringFromQueryString("id", "");

                        if (bt.IsExistPrivateCustomer(new Guid(strJson)))
                        {
                            //该客户已是私海客户!请即使刷新页面!
                            HttpContext.Current.Response.Write("2");
                            return;
                        }
                        else
                        {
                            if (bll.CheckCustomerIsPrevateState(new Guid(strJson)))
                            {
                                DbSql db = new DbSql();
                                int iCount = db.GetRowCount("CrmPrivateCustom", " AddUser='" + this.UserId + "' and CustomUser='" + this.UserId + "'");
                                int iAllCount = bt.GetPrivateNum("PrivateAreaTotalSet");
                                if (iCount >= iAllCount)
                                {
                                    //您的私海客户数已达到设置的私海总数,如有疑问请联系管理员!
                                    HttpContext.Current.Response.Write("3");
                                    return;
                                }
                                else
                                {
                                    strSql = string.Format("Exec sp_EditCrmCustomerToPrivate '{0}','{1}','{2}','{3}'",
                                                strJson, this.UserId, 0, "00000000-0000-0000-0000-000000000000");
                                }
                            }
                            else
                            {
                                //该客户已被处理，不是公海客户，请及时刷新数据!
                                HttpContext.Current.Response.Write("4");
                                return;
                            }
                        } 
                    }
                    #endregion
                    #region ---- CrmWillCustomer(公海转意向客户) ----
                    else if (strEntity == "CrmWillCustomer")
                    {
                        strJson = this.GetStringFromQueryString("id", "");
                        if (bll.CheckCustomerIsPrevateState(new Guid(strJson)))
                        {
                            if (bt.IsExistWillCustomer(new Guid(strJson), new Guid(this.UserId.ToString())))
                            {
                                //该客户已是意向客户!
                                HttpContext.Current.Response.Write("2");
                                return;
                            }
                            else
                            {
                                strSql = string.Format("Exec sp_EditCrmCustomerToWill '{0}','{1}'", strJson, this.UserId);
                            }
                        }
                        else
                        {
                            //该客户已被处理，不是公海客户，请及时刷新数据!
                            HttpContext.Current.Response.Write("3");
                            return;
                        }
                    }
                    #endregion
                    #region---- CrmPublicCustom(意向客户转向公海) ----
                    else if (strEntity == "CrmWillCustomToPublic")
                    {
                        string strCustomerId = this.GetStringFromQueryString("cid", "");
                        if (bll.CheckCustomerIsPrevateState(new Guid(strCustomerId)))
                        {
                            strJson = this.GetStringFromQueryString("id", "");
                            strSql = string.Format("Exec sp_EditCrmCustomerToPublic '{0}','{1}','{2}'", strJson, this.UserId, strCustomerId);
                        }
                        else
                        {
                            HttpContext.Current.Response.Write("该客户已被处理，请及时刷新数据!");
                            return;
                        }
                    }
                    #endregion
                    #region ---- CrmPrivateCustom(意向客户转向私海) ----
                    else if (strEntity == "CrmWillCustomToPrivate")
                    {
                        string strCustomerId = this.GetStringFromQueryString("cid", "");
                        if (bll.CheckCustomerIsPrevateState(new Guid(strCustomerId)))
                        {
                            strJson = this.GetStringFromQueryString("id", "");
                            DbSql db = new DbSql();
                            int iCount = db.GetRowCount("CrmPrivateCustom", " AddUser='" + this.UserId + "' and CustomUser='" + this.UserId + "'");
                            int iAllCount = bt.GetPrivateNum("PrivateAreaTotalSet");
                            if (iCount >= iAllCount)
                            {
                                HttpContext.Current.Response.Write("您的私海客户数已达到设置的私海总数,如有疑问请联系管理员!");
                                return;
                            }
                            else
                            {
                                strSql = string.Format("Exec sp_EditCrmCustomerToPrivate '{0}','{1}','{2}','{3}'",
                                            strCustomerId, this.UserId, 1, strJson);
                            }
                        }
                        else
                        {
                            HttpContext.Current.Response.Write("该客户已被处理，请及时刷新数据!");
                            return;
                        }
                    }
                    #endregion
                    #region ------- 添加附件(CrmCustomerAttach) -------
                    else if (strEntity == "CrmCustomerAttach")
                    {
                        CrmCustomerAttach instance = Globals.JSonToObject<CrmCustomerAttach>(strJson);
                        Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                        Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);
                        Globals.SetPropertyValue(instance, "ID", Guid.NewGuid());
                        string strCustomerId = this.GetStringFromQueryString("id", "");
                        strSql = string.Format("Exec sp_AddCrmCustomerAttach '{0}','{1}','{2}','{3}','{4}','{5}','{6}'",
                                    instance.ID, strCustomerId, instance.Caption, instance.Size,
                                    instance.Address, instance.Explain, instance.AddUser);
                    }
                    #endregion
                    #region------ 客户分配保存一条数据至私海 (CrmCustomerInfo) ---
                    else if (strEntity == "CrmCustomerInfo")
                    {
                        strJson = this.GetStringFromQueryString("id",""); //客户ID
                        strSql = string.Format("Exec sp_AddCrmCustomerInfoToPrivate '{0}','{1}','{2}','{3}','{4}'", strJson, this.UserId,
                                            "客户分配时插入的对应客户数据", this.UserId, DateTime.Now);
                    }
                    #endregion
                    #region-------------- CrmCustomerReturn(退回) --------------
                    else if (strEntity == "CrmCustomerReturn")
                    {
                        instanceReturn = Globals.JSonToObject<CrmCustomerReturn>(strJson);
                        Globals.SetPropertyValue(instanceReturn, "AddUser", this.UserId);
                        Globals.SetPropertyValue(instanceReturn, "AddTime", System.DateTime.Now);
                        Globals.SetPropertyValue(instanceReturn, "ModifyUser", "00000000-0000-0000-0000-000000000000");
                        Globals.SetPropertyValue(instanceReturn, "ModifyTime", "1900-01-01");
                        strSql = string.Format("Exec sp_AddCrmCustomerReturn '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}'",
                                        instanceReturn.CustomerId, instanceReturn.ReciveUser, instanceReturn.CustomerState,
                                        instanceReturn.ReturnReason, instanceReturn.AddUser, instanceReturn.AddTime,
                                        instanceReturn.ModifyUser, instanceReturn.ModifyTime);
                    }
                    #endregion
                    int iResult = blls.RunSqlCommand(strSql);
                    if (iResult > 0)
                    {
                        if (strEntity == "CrmCustomerReturn")
                        {
                            string strReturn = this.ReturnSaveMsg("客户退回", "客户退回信息,请尽快修改客户信息!", instanceReturn.AddUser, instanceReturn.ReciveUser);
                        }
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("0");
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }


        /// <summary>
        /// 退回时保存消息
        /// </summary>
        /// <returns></returns>
        private string ReturnSaveMsg(string msgTitle, string msgContent, Guid sendUser, Guid receiverUser)
        {
            try
            {
                BDatMessageQueue target = new BDatMessageQueue(); // TODO: 初始化为适当的值
                DatMessageQueue msg = DatMessageQueue.New(); // TODO: 初始化为适当的值
                msg.MsgID = Guid.NewGuid();
                msg.Title = msgTitle.ToString();
                //msg.MsgTemplate = "";
                msg.MsgContent = msgContent.ToString();
                msg.MessageType = "0";
                msg.ExpectTime = DateTime.Now;
                msg.AddUser = sendUser;
                msg.PushTime = DateTime.Now;
                //msg.QueryID = new Guid("F8ED27B4-B5BC-4497-9881-FE3AD0512125");//关联信息来源的编号

                IList<DatMessageReceiver> MessageReceiver = new List<DatMessageReceiver>(); // TODO: 初始化为适当的值
                DatMessageReceiver mr1 = DatMessageReceiver.New();
                mr1.MsItemID = Guid.NewGuid();
                mr1.MsgID = msg.MsgID;
                mr1.ReceiverID = receiverUser;
                mr1.ReceiverType = "U";
                MessageReceiver.Add(mr1);
                target.AddMessage(msg, MessageReceiver);
                BDatMessageQueue target1 = new BDatMessageQueue(); // TODO: 初始化为适当的值
                DateTime CurrentTime = DateTime.Now; // TODO: 初始化为适当的值
                target1.PushMessages(CurrentTime);
                return "1";
            }
            catch
            {
                return "0";
            }
        }


        /// <summary>
        /// 自定义查看方法
        /// </summary>
        /// <param name="strEntity">实体</param>
        /// <param name="strJson">JSON数据</param>
        private void RunCheck(string strEntity, string strJson)
        {
            switch (strEntity)
            {
                case "CustomerName":
                    CheckCustomerNameIsExists(strJson);
                    break;
                case "CustomerTel":
                    CheckCustomerTelIsExists(strJson);
                    break;
                case "CrmCustomer":
                    LoadCustomerName(strJson);
                    break;
                case "CrmCustomerCheck":
                    CheckCustomerIsPrevateState(strJson);
                    break;
                case "CrmCustomerCheckField":
                    CheckCrmCustomerOrder(strJson);
                    break;
                case "V_DatEmployeeForUser":
                    SelectDatEmployeeByDeptId(strJson);
                    break;
                case "V_DatEmployeeForName":
                    SelectDatEmployeeByName(strJson);
                    break;
                case "CrmCustomerReturn":
                    CheckCrmCustomerReturn(strJson);
                    return;
                case "CrmCustomerOrderAgree":
                    WorkFlowCrmCustomerOrderAgree(strJson);
                    break;
                case "CrmCustomerOrderUnAgree":
                    WorkFlowCrmCustomerOrderUnAgree(strJson);
                    break;
                case "CrmDeliverMajorUnAgree":
                    WorkFlowCrmDeliverMajorUnAgree(strJson);
                    break;
                case "DatUser":
                    CheckDatUserByUName(strJson);
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 保存客户信息时检查客户数据
        /// </summary>
        /// <param name="strEntity">实体</param>
        /// <param name="strJson">JSON数据</param>
        private void CheckCustomerNameIsExists(string strJson)
        {
            try
            {   
                strJson = this.GetStringFromQueryString("id", "");
                string strFlag = this.GetStringFromQueryString("temp", "");
                string strName = this.GetStringFromQueryString("name", "");
                string[] strValue = strName.Split(',');     
                if (strValue.Length >= 1)
                {
                    if (strValue.Length == 1)  //单击检查按钮
                    {
                        //检查公海表(CrmCustomer)中客户信息
                        if (bll.CrmCustomerNameIsExists(new Guid(strJson), strFlag, strValue[0]))
                        {
                            HttpContext.Current.Response.Write("1");  //客户名已存在
                        }
                        else
                        {
                            //检查CrmCustomerInfo表中客户信息
                            if (bll.CrmCustomerInfoNameIsExists(new Guid(strJson), strFlag, strValue[0]))
                            {
                                HttpContext.Current.Response.Write("11");  //CrmCustomerInfo表客户名已存在
                            }
                            else
                            {
                                HttpContext.Current.Response.Write("2");  //客户名不存在
                            }
                        }
                    }
                    else if (strValue.Length == 3)  //保存时自动检查
                    {
                        if (strFlag == "1") //新增检查
                        {
                            string startTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00.000";
                            string endTime = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:00.000";
                            string userId = this.UserId.ToString();
                            int iSetCustomerCount = bll.GetPrivateNum("InsertCustomerTotal");
                            int iAllCustomerCount = bll.GetCrmCustomerCount(new Guid(userId), startTime, endTime);
                            if (iAllCustomerCount >= iSetCustomerCount)
                            {
                                HttpContext.Current.Response.Write("5");  //当前用户添加的客户数超过设置的客户总数
                            }
                            else
                            {
                                DataCheck(strJson, strFlag, strValue);
                            }
                        }
                        else
                        {
                            DataCheck(strJson, strFlag, strValue);
                        }
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");  //异常
            }
        }
        private void DataCheck(string strJson, string strFlag, string[] strValue) 
        {
            //检查公海表(CrmCustomer)中客户信息
            if (bll.CrmCustomerNameIsExists(new Guid(strJson), strFlag, strValue[0]))
            {
                HttpContext.Current.Response.Write("1");  //客户名已存在
            }
            else
            {
                //检查CrmCustomerInfo表中客户信息
                if (bll.CrmCustomerInfoNameIsExists(new Guid(strJson), strFlag, strValue[0]))
                {
                    HttpContext.Current.Response.Write("11");  //客户名已存在
                }
                else
                {
                    //决策人和决策人手机已存在(CrmCustomer)
                    if (bll.CrmCustomerMakerandTel(new Guid(strJson), strFlag, strValue[1], strValue[2]))
                    {
                        HttpContext.Current.Response.Write("3");  //决策人和决策人手机已存在
                    }
                    else
                    {
                        //决策人和决策人手机已存在(CrmCustomerInfo)
                        if (bll.CrmCustomerInfoMakerandTel(new Guid(strJson), strFlag, strValue[1], strValue[2]))
                        {
                            HttpContext.Current.Response.Write("33");  //决策人和决策人手机已存在
                        }
                        else
                        {
                            HttpContext.Current.Response.Write("4");  //决策人和决策人手机不存在
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 检查决策人手机是否已存在
        /// </summary>
        /// <param name="strJson"></param>
        private void CheckCustomerTelIsExists(string strJson)
        {
            try
            {
                strJson = this.GetStringFromQueryString("id", "");
                string strFlag = this.GetStringFromQueryString("temp", "");
                string strName = this.GetStringFromQueryString("name", "");
                //决策人和决策人手机已存在(CrmCustomer)
                if (bll.CrmCustomerTelIsExists(new Guid(strJson), strFlag, strName))
                {
                    HttpContext.Current.Response.Write("1");  //决策人和决策人手机已存在
                }
                else
                {
                    //决策人和决策人手机已存在(CrmCustomerInfo)
                    if (bll.CrmCustomerInfoTelIsExists(new Guid(strJson), strFlag, strName))
                    {
                        HttpContext.Current.Response.Write("11");  //决策人和决策人手机已存在
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("2");  //决策人和决策人手机不存在
                    }
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");  //异常
            }
        }
        /// <summary>
        /// 联想获取用户名
        /// </summary>
        /// <param name="strJson">JSON数据</param>
        private void LoadCustomerName(string strJson)
        {
            IList<BaseEntity> listCustomerName = new List<BaseEntity>();
            DbSql db = new DbSql();
            string strSql = string.Format("select ID as id,CustomerName as fname from CrmCustomer where CustomerName like '%{0}%'", strJson);
            DataTable dt = db.ExecuteQuery(strSql);
            string str = Globals.DataTableToJSON(dt);
            HttpContext.Current.Response.Write(str);
        }
        /// <summary>
        /// 开始按钮事件前判断当前客户数据是否可进行相应操作
        /// </summary>
        /// <param name="strJson"></param>
        private void CheckCustomerIsPrevateState(string strJson)
        {
            try
            {
                strJson = this.GetStringFromQueryString("id", "");
                if (strJson == "0")  //点击新增时检查是否还可以添加客户
                {
                    string startTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00.000";
                    string endTime = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:00.000";
                    string userId = this.UserId.ToString();
                    int iSetCustomerCount = bll.GetPrivateNum("InsertCustomerTotal");
                    int iAllCustomerCount = bll.GetCrmCustomerCount(new Guid(userId), startTime, endTime);
                    if (iAllCustomerCount >= iSetCustomerCount)
                    {
                        HttpContext.Current.Response.Write("2");  //当前用户添加的客户数超过设置的客户总数
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("1");
                    }
                }
                else
                {
                    if (bll.CheckCustomerIsPrevateState(new Guid(strJson)))
                    {
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("2");   //该客户已被处理，不是公海客户，请及时刷新数据
                    }
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 订单变更时进行判断操作
        /// </summary>
        /// <param name="strJson"></param>
        private void CheckCrmCustomerOrder(string strJson)
        {
            try
            {
                BTCrmCrustomerOrder bllOrder = new BTCrmCrustomerOrder();
                strJson = this.GetStringFromQueryString("id", "");
                string strType = this.GetStringFromQueryString("type", ""); //0:约场订单 1:销售订单
                V_CrmCustomerOrder Orders = bllOrder.GetAllCrmCustomerOrder(new Guid(strJson));
                if (strType == "0")
                {
                    if (Orders.TypeID.ToString().ToUpper() == "5E50217A-414E-46D5-89BC-348AD0145FFC")
                    {
                        CrmCustomerOrder(Orders.StateID.ToString().ToUpper());
                    }
                    else
                    {
                        //点击约场订单变更时选中的信息不是约场订单
                        HttpContext.Current.Response.Write("6");
                        return;
                    }
                }
                else
                {
                    if (Orders.TypeID.ToString().ToUpper() == "5E50217A-414E-46D5-89BC-348AD0145FFC")
                    {
                        //点击销售订单变更时选中的信息不是销售订单
                        HttpContext.Current.Response.Write("7");
                        return;
                    }
                    else
                    {
                        CrmCustomerOrder(Orders.StateID.ToString().ToUpper());
                    }
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("操作异常，如有疑问请联系管理员!");
            }
        }
        private void CrmCustomerOrder(string StateId)
        {
            if (StateId == "319FDCFA-3948-495B-88B0-1EAB7DC9F138")
            {
                HttpContext.Current.Response.Write("3");//您当前的订单处于 签核中 状态，不能变更!
                return;
            }
            else if (StateId == "BDDCAF31-98D4-423A-9275-9288F85E2847")
            {
                HttpContext.Current.Response.Write("4");//您当前的订单处于 结案 状态，不能变更!
                return;
            }
            else if (StateId == "C2AF1C1F-6937-40EE-8D40-2E6203E34119")
            {
                HttpContext.Current.Response.Write("5");//您当前的订单处于 报废 状态，不能变更!
                return;
            }
            else if (StateId == "C3DACC37-2463-458F-BC45-14AD8722BA45")
            {
                HttpContext.Current.Response.Write("1"); //新建状态
                return;
            }
            else
            {
                HttpContext.Current.Response.Write("2");
                return;
            }
        }
        /// <summary>
        /// 共享客户时更加部门ID查询出部门所有的人
        /// </summary>
        /// <param name="strJson"></param>
        private void SelectDatEmployeeByDeptId(string strJson)
        {
            try
            {
                string strlistEmployee = "";
                strJson = this.GetStringFromQueryString("id", "");
                IList<V_DatEmployeeForUser> listEmployee = bll.GetDatEmployeeByDeptId(strJson);
                if (listEmployee != null && listEmployee.Count > 0)
                {
                    IList<BaseEntity> _listEmployee = new List<BaseEntity>();
                    foreach (var _e in listEmployee)
                    {
                        _listEmployee.Add(_e);
                    }
                    strlistEmployee = "[" + _listEmployee.ToJSON().Replace("\n", "").Replace("\r", "").Replace("@@", "") + "]";
                    HttpContext.Current.Response.Write(strlistEmployee);
                }
                else 
                {
                    HttpContext.Current.Response.Write(strlistEmployee);
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 根据名称查找所有职员信息(分配和共享时查询用)
        /// </summary>
        /// <param name="strJson"></param>
        private void SelectDatEmployeeByName(string strJson)
        {
            try
            {
                string strlistEmployee = "";
                strJson = this.GetStringFromQueryString("id", "");
                IList<V_DatEmployeeForUser> listEmployee = bll.GetDatEmployeeByName(strJson);
                if (listEmployee != null && listEmployee.Count > 0)
                {
                    IList<BaseEntity> _listEmployee = new List<BaseEntity>();
                    foreach (var _e in listEmployee)
                    {
                        _listEmployee.Add(_e);
                    }
                    strlistEmployee = "[" + _listEmployee.ToJSON().Replace("\n", "").Replace("\r", "").Replace("@@", "") + "]";
                    HttpContext.Current.Response.Write(strlistEmployee);
                }
                else
                {
                    HttpContext.Current.Response.Write(strlistEmployee);
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 退回修改客户信息判断
        /// </summary>
        /// <param name="strJson"></param>
        private void CheckCrmCustomerReturn(string strJson)
        {
            BTCrmCustomer bt = new BTCrmCustomer();
            try
            {
                strJson = this.GetStringFromQueryString("id", ""); //客户ID
                int iAllCount = bt.GetPrivateNum("CustomerReturnTime");
                CrmCustomerReturn customerReturn = bt.GetCrmCustomerReturn(new Guid(strJson));
                DateTime dtTime = customerReturn.AddTime.AddDays(iAllCount);
                DateTime dtNow = DateTime.Now;
                if (dtNow > dtTime)
                {
                    //任何人可以修改
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    if (customerReturn.ReciveUser.ToString().Equals(this.UserId.ToString()))
                    {
                        //当前时间内只能接收人自己修改!
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        //当前用户不是接收人不能修改该客户信息!
                        HttpContext.Current.Response.Write("2");
                    }
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 消息订单流程同意
        /// </summary>
        /// <param name="strJson"></param>
        private void WorkFlowCrmCustomerOrderAgree(string strJson)
        {
            try
            {
                strJson = this.GetStringFromQueryString("OperatorInstanceId", ""); //流程操作ID
                string strWorkTaskInsId = this.GetStringFromQueryString("WorkTaskInsId", "");
                CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                string msgClaim = client.TaskClaim(this.User.LoginName, strJson);
                string msgRun = client.Run(this.User.LoginName, strJson, "提交");
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 消息订单流程不同意(退回)
        /// </summary>
        /// <param name="strJson"></param>
        private void WorkFlowCrmCustomerOrderUnAgree(string strJson)
        {
            try
            {
                strJson = this.GetStringFromQueryString("OperatorInstanceId", ""); //流程操作ID
                string strWorkFlowId = this.GetStringFromQueryString("WorkflowId", ""); //
                string strWorkTaskId = this.GetStringFromQueryString("WorktaskId", "");
                string strWorkFlowInsId = this.GetStringFromQueryString("WorkflowInsId", "");
                string strWorkTaskInsId = this.GetStringFromQueryString("WorktaskInsId", "");
                string strMessage = this.GetStringFromQueryString("msg", "");//退回意见
                CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                string msgClaim = client.TaskClaim(this.User.LoginName, strJson);

                CrmWorkFlowService.AuditMessage am = new CrmWorkFlowService.AuditMessage();
                am.AuditId = Guid.NewGuid().ToString();
                am.WorkflowId = strWorkFlowId;
                am.WorkflowInsId = strWorkFlowInsId;
                am.WorktaskId = strWorkTaskId;
                am.WorktaskInsId = strWorkTaskInsId;
                am.OperatorInsId = strJson;
                am.AuditUserId = this.User.LoginName;
                am.AuditUserName = this.User.UName;
                am.AuditArch = "";
                am.AuditDuty = "";
                am.AuditResult = "拒绝";
                am.Message = strMessage;
                client.InsertAuditMessage(am);

                string msgBack = client.TaskBack(this.User.LoginName, strJson);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 大课流程退回
        /// </summary>
        /// <param name="strJson"></param>
        private void WorkFlowCrmDeliverMajorUnAgree(string strJson)
        {
            try
            {
                strJson = this.GetStringFromQueryString("OperatorInstanceId", ""); //流程操作ID
                string strWorkFlowId = this.GetStringFromQueryString("WorkflowId", ""); //
                string strWorkTaskId = this.GetStringFromQueryString("WorktaskId", "");
                string strWorkFlowInsId = this.GetStringFromQueryString("WorkflowInsId", "");
                string strWorkTaskInsId = this.GetStringFromQueryString("WorktaskInsId", "");
                string strMessage = this.GetStringFromQueryString("msg","");//退回意见
                CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                string msgClaim = client.TaskClaim(this.User.LoginName, strJson);

                CrmWorkFlowService.AuditMessage am = new CrmWorkFlowService.AuditMessage();
                am.AuditId = Guid.NewGuid().ToString();
                am.WorkflowId = strWorkFlowId;
                am.WorkflowInsId = strWorkFlowInsId;
                am.WorktaskId = strWorkTaskId;
                am.WorktaskInsId = strWorkTaskInsId;
                am.OperatorInsId = strJson;
                am.AuditUserId = this.User.LoginName;
                am.AuditUserName = this.User.UName;
                am.AuditArch = "";
                am.AuditDuty = "";
                am.AuditResult = "拒绝";
                am.Message = strMessage;
                client.InsertAuditMessage(am);

                string msgBack = client.TaskBack(this.User.LoginName, strJson);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 根据名称判断用户是否存在
        /// </summary>
        /// <param name="useName"></param>
        private void CheckDatUserByUName(string useName)
        {
            try
            {
                BUser buser = new BUser();
                DatUser du = buser.GetDatUserByUName(useName);
                if (du != null)
                {
                    HttpContext.Current.Response.Write(du.UserID);
                }
                else
                {
                    HttpContext.Current.Response.Write("1");//系统中不存在改用户
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }


        /// <summary>
        /// 插入数据(保存订单)
        /// </summary>
        /// <param name="strEntity">实体</param>
        /// <param name="strJson">JSON数据</param>
        private void InsertIntoInfo(string strEntity, string strJson)
        {
            switch (strEntity)
            {
                case "CrmCustomerOrderField":
                case "CrmCustomerOrder":
                    InsertOrder(strEntity, strJson);
                    break;
                case "CrmPay":
                    InsertPay(strEntity, strJson);
                    break;
                case "CrmDeliverMajor":
                    InsertDeliverMajor(strEntity, strJson);
                    break;
                case "CrmDeliverMajorProject":
                    InsertDeliverMajorProject(strEntity, strJson);
                    break;
                case "CrmLinkMan":
                    InsertCrmLinkMan(strEntity, strJson);
                    break;
                case "CrmActivity":
                case "CrmActivityInfo":
                    InsertCrmActivity(strEntity,strJson);
                    break;
                case "CrmCustomerDatLog":
                    InsertCrmCustomerOperator(strEntity, strJson);
                    break;
                default:
                    break;
            }
        }
        private void InsertPay(string strEntity, string strJson)
        {
            try
            {
                int iResult = 0;
                IDataParameter[] _Parameters = new IDataParameter[] { };
                DbSql db = new DbSql();
                CrmPay instance = (CrmPay)Globals.JSonToObject<CrmPay>(strJson);
                Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                Globals.SetPropertyValue(instance, "Addtime", System.DateTime.Now);
                BUser bUser = new BUser();
                DatUser dus= bUser.GetDatUserByUserId(new Guid(instance.CheckUser));
                SqlParameter Code = new SqlParameter("@Code", SqlDbType.Char, 50);
                Code.Direction = ParameterDirection.Input;
                Code.Value = instance.Code;
                SqlParameter CustomerId = new SqlParameter("@CustomerId", SqlDbType.UniqueIdentifier, 50);
                CustomerId.Direction = ParameterDirection.Input;
                CustomerId.Value = instance.CustomerId;
                SqlParameter DeptId = new SqlParameter("@DeptId", SqlDbType.UniqueIdentifier, 50);
                DeptId.Direction = ParameterDirection.Input;
                DeptId.Value = instance.DeptId;
                SqlParameter Date = new SqlParameter("@Date", SqlDbType.DateTime, 50);
                Date.Direction = ParameterDirection.Input;
                Date.Value = instance.Date;
                
                SqlParameter ValutaID = new SqlParameter("@ValutaID", SqlDbType.UniqueIdentifier, 50);
                ValutaID.Direction = ParameterDirection.Input;
                ValutaID.Value = instance.ValutaID;
                SqlParameter PillID = new SqlParameter("@PillID", SqlDbType.UniqueIdentifier, 50);
                PillID.Direction = ParameterDirection.Input;
                PillID.Value = instance.PillID;
                SqlParameter InvoiceNum = new SqlParameter("@InvoiceNum", SqlDbType.NVarChar, 50);
                InvoiceNum.Direction = ParameterDirection.Input;
                InvoiceNum.Value = instance.@InvoiceNum;
                SqlParameter Explain = new SqlParameter("@Explain", SqlDbType.NVarChar, 1000);
                Explain.Direction = ParameterDirection.Input;
                Explain.Value = instance.Explain;
                SqlParameter AddUser = new SqlParameter("@AddUser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = instance.AddUser;
                SqlParameter AddTime = new SqlParameter("@AddTime", SqlDbType.DateTime, 50);
                AddTime.Direction = ParameterDirection.Input;
                AddTime.Value = instance.Addtime;
                SqlParameter PayDate = new SqlParameter("@PayDate", SqlDbType.DateTime, 50);
                PayDate.Direction = ParameterDirection.Input;
                PayDate.Value = instance.PayDate;
                SqlParameter StateID = new SqlParameter("@State", SqlDbType.UniqueIdentifier, 50);
                StateID.Direction = ParameterDirection.Input;
                StateID.Value = instance.State;
                SqlParameter WorkTaskId = new SqlParameter("@WorkTaskId", SqlDbType.NVarChar, 50);
                WorkTaskId.Direction = ParameterDirection.Input;
                WorkTaskId.Value = instance.WorkTaskId;
                SqlParameter WorkFlowId = new SqlParameter("@WorkFlowId", SqlDbType.NVarChar, 50);
                WorkFlowId.Direction = ParameterDirection.Input;
                WorkFlowId.Value = instance.WorkFlowId;
                SqlParameter WorkFlowInsId = new SqlParameter("@WorkFlowInsId", SqlDbType.NVarChar, 50);
                WorkFlowInsId.Direction = ParameterDirection.Input;
                WorkFlowInsId.Value = instance.WorkFlowInsId;
                SqlParameter WorkTaskInsId = new SqlParameter("@WorkTaskInsId", SqlDbType.NVarChar, 50);
                WorkTaskInsId.Direction = ParameterDirection.Input;
                WorkTaskInsId.Value = instance.WorkTaskInsId;
                SqlParameter CheckUser = new SqlParameter("@CheckUser", SqlDbType.NVarChar, 50);
                CheckUser.Direction = ParameterDirection.Input;
                CheckUser.Value =dus==null?"": dus.LoginName;
                SqlParameter ProduectList = new SqlParameter("@ProduectList", SqlDbType.NVarChar, 4000);
                ProduectList.Direction = ParameterDirection.Input;
                ProduectList.Value = instance.ProduectList;

                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;

               
                    SqlParameter OrderType = new SqlParameter("@OrderType", SqlDbType.Int, 1);
                    OrderType.Direction = ParameterDirection.Input;
                    OrderType.Value = 0;
                    _Parameters = new IDataParameter[] { Code, CustomerId,ValutaID, DeptId,PillID,InvoiceNum, StateID,Date,PayDate,   
                           Explain,WorkTaskId,WorkFlowId,WorkFlowInsId,WorkTaskInsId,CheckUser, AddUser, AddTime,  
                        ProduectList, ReturnValue};

                    string strSql = db.RunProcedureReturnString("sp_AddCrmPay", _Parameters, out iResult);
                if (strSql == "1")
                {
                    string userId = this.User.LoginName;
                    CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                    string msg1 = client.Start(userId, instance.WorkFlowId, instance.WorkTaskId, instance.WorkFlowInsId, instance.WorkTaskInsId, client.GetWorkFlowNO(), "提交", "3", "缴款单", false);
                    //Server.Transfer("../../Crm/BasePages/tooltip.aspx?worktaskInstanceId=" + instance.WorkTaskId);
                    HttpContext.Current.Response.Write("1");
                    
                }
                else
                {
                    HttpContext.Current.Response.Write("保存数据失败!");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("保存数据失败!");
            }
        }
        private void InsertOrder(string strEntity,string strJson)
        {
            int iResult = 0;
            IDataParameter[] _Parameters = new IDataParameter[] { };
            DbSql db = new DbSql();
            try
            {
                CrmCustomerOrder instance = (CrmCustomerOrder)Globals.JSonToObject<CrmCustomerOrder>(strJson);
                Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);

                SqlParameter ID = new SqlParameter("@ID", SqlDbType.UniqueIdentifier, 50);
                ID.Direction = ParameterDirection.Input;
                ID.Value = instance.ID;
                SqlParameter Code = new SqlParameter("@Code", SqlDbType.Char, 50);
                Code.Direction = ParameterDirection.Input;
                Code.Value = instance.Code;
                SqlParameter CustomerId = new SqlParameter("@CustomerId", SqlDbType.UniqueIdentifier, 50);
                CustomerId.Direction = ParameterDirection.Input;
                CustomerId.Value = instance.CustomerId;
                SqlParameter DeptId = new SqlParameter("@DeptId", SqlDbType.UniqueIdentifier, 50);
                DeptId.Direction = ParameterDirection.Input;
                DeptId.Value = instance.DeptId;
                SqlParameter Date = new SqlParameter("@Date", SqlDbType.DateTime, 50);
                Date.Direction = ParameterDirection.Input;
                Date.Value = instance.Date;
                SqlParameter TypeID = new SqlParameter("@TypeID", SqlDbType.UniqueIdentifier, 50);
                TypeID.Direction = ParameterDirection.Input;
                TypeID.Value = instance.TypeID;
                SqlParameter ValutaID = new SqlParameter("@ValutaID", SqlDbType.UniqueIdentifier, 50);
                ValutaID.Direction = ParameterDirection.Input;
                ValutaID.Value = instance.ValutaID;
                SqlParameter PillID = new SqlParameter("@PillID", SqlDbType.UniqueIdentifier, 50);
                PillID.Direction = ParameterDirection.Input;
                PillID.Value = instance.PillID;
                SqlParameter CourseLoyoutID = new SqlParameter("@CourseLoyoutID", SqlDbType.UniqueIdentifier, 50);
                CourseLoyoutID.Direction = ParameterDirection.Input;
                CourseLoyoutID.Value = instance.CourseLoyoutID;
                SqlParameter PaymentId = new SqlParameter("@PaymentId", SqlDbType.UniqueIdentifier, 50);
                PaymentId.Direction = ParameterDirection.Input;
                PaymentId.Value = instance.PaymentId;
                SqlParameter Explain = new SqlParameter("@Explain", SqlDbType.NVarChar, 1000);
                Explain.Direction = ParameterDirection.Input;
                Explain.Value = instance.Explain;
                SqlParameter AddUser = new SqlParameter("@AddUser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = instance.AddUser;
                SqlParameter AddTime = new SqlParameter("@AddTime", SqlDbType.DateTime, 50);
                AddTime.Direction = ParameterDirection.Input;
                AddTime.Value = instance.AddTime;
                SqlParameter TotalMoney = new SqlParameter("@TotalMoney", SqlDbType.Decimal, 20);
                TotalMoney.Direction = ParameterDirection.Input;
                TotalMoney.Value = instance.TotalMoney;
                SqlParameter StateID = new SqlParameter("@StateID", SqlDbType.UniqueIdentifier, 50);
                StateID.Direction = ParameterDirection.Input;
                StateID.Value = instance.StateID;

                SqlParameter ProduectList = new SqlParameter("@ProduectList", SqlDbType.NVarChar, 4000);
                ProduectList.Direction = ParameterDirection.Input;
                ProduectList.Value = instance.ProduectList;
                SqlParameter CustomerZjList = new SqlParameter("@CustomerZjList", SqlDbType.NVarChar, 4000);
                CustomerZjList.Direction = ParameterDirection.Input;
                CustomerZjList.Value = instance.CustomerZjList;
                SqlParameter CustomerServerList = new SqlParameter("@CustomerServerList", SqlDbType.NVarChar, 4000);
                CustomerServerList.Direction = ParameterDirection.Input;
                CustomerServerList.Value = instance.CustomerServerList;

                SqlParameter TeacherId = new SqlParameter("@TeacherId", SqlDbType.UniqueIdentifier, 50);
                TeacherId.Direction = ParameterDirection.Input;
                TeacherId.Value = instance.TeacherId;
                SqlParameter TeacherTime = new SqlParameter("@TeacherTime", SqlDbType.DateTime, 50);
                TeacherTime.Direction = ParameterDirection.Input;
                TeacherTime.Value = instance.TeacherTime;
                SqlParameter TeacherAddress = new SqlParameter("@TeacherAddress", SqlDbType.NVarChar, 50);
                TeacherAddress.Direction = ParameterDirection.Input;
                TeacherAddress.Value = instance.TeacherAddress;
                SqlParameter TeacherType = new SqlParameter("@TeacherType", SqlDbType.NVarChar, 50);
                TeacherType.Direction = ParameterDirection.Input;
                TeacherType.Value = instance.TeacherType;


                SqlParameter WorkFlowId = new SqlParameter("@WorkFlowId", SqlDbType.NVarChar, 50);
                WorkFlowId.Direction = ParameterDirection.Input;
                WorkFlowId.Value = instance.WorkFlowId;
                SqlParameter WorkTaskId = new SqlParameter("@WorkTaskId", SqlDbType.NVarChar, 50);
                WorkTaskId.Direction = ParameterDirection.Input;
                WorkTaskId.Value = instance.WorkTaskId;
                SqlParameter WorkFlowInsId = new SqlParameter("@WorkFlowInsId", SqlDbType.NVarChar, 50);
                WorkFlowInsId.Direction = ParameterDirection.Input;
                WorkFlowInsId.Value = instance.WorkFlowInsId;
                SqlParameter WorkTaskInsId = new SqlParameter("@WorkTaskInsId", SqlDbType.NVarChar, 50);
                WorkTaskInsId.Direction = ParameterDirection.Input;
                WorkTaskInsId.Value = instance.WorkTaskInsId;


                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;

                SqlParameter OrderType = new SqlParameter();
                if (strEntity == "CrmCustomerOrderField")  //约场订单
                {
                    OrderType = new SqlParameter("@OrderType", SqlDbType.Int, 1);
                    OrderType.Direction = ParameterDirection.Input;
                    OrderType.Value = 0;
                }
                else if (strEntity == "CrmCustomerOrder")  //销售订单
                {
                    OrderType = new SqlParameter("@OrderType", SqlDbType.Int, 1);
                    OrderType.Direction = ParameterDirection.Input;
                    OrderType.Value = 1;
                }
                _Parameters = new IDataParameter[] { ID,Code, CustomerId, DeptId, Date, TypeID, ValutaID, 
                        PillID, CourseLoyoutID, PaymentId, Explain, AddUser, AddTime, TotalMoney, StateID, OrderType,
                        ProduectList,CustomerZjList,CustomerServerList,TeacherId,TeacherTime,TeacherAddress,TeacherType,
                        WorkFlowId,WorkTaskId,WorkFlowInsId,WorkTaskInsId, ReturnValue};
                string strSql = db.RunProcedureReturnString("sp_AddCrmCustomerOrder", _Parameters, out iResult);
                if (strSql == "1")
                {
                    if (TypeID.Value.ToString().ToUpper() == "5E50217A-414E-46D5-89BC-348AD0145FFC" ||
                        TypeID.Value.ToString().ToUpper() == "53C8DAE4-F3C9-4995-BB6A-560123574B81") //类型为一推|约场
                    {
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        string userId = this.User.LoginName;
                        CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                        string msg1 = client.Start(userId, WorkFlowId.Value.ToString(), WorkTaskId.Value.ToString(),
                             WorkFlowInsId.Value.ToString(), WorkTaskInsId.Value.ToString(), client.GetWorkFlowNO(), "提交", "3", "销售订单", false);
                        HttpContext.Current.Response.Write("3");
                    }
                }
                else if (strSql == "2")
                {
                    //约场订单中该讲师在当前时间段已安排讲场!
                    HttpContext.Current.Response.Write("2"); 
                }
                else
                {
                    HttpContext.Current.Response.Write("保存数据失败!");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("保存数据失败!");
            }
        }
        private void InsertDeliverMajor(string strEntity, string strJson)
        {
            int iResult = 0;
            IDataParameter[] _Parameters = new IDataParameter[] { };
            DbSql db = new DbSql();
            try
            {
                CrmDeliverMajor instance = (CrmDeliverMajor)Globals.JSonToObject<CrmDeliverMajor>(strJson);
                Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);

                SqlParameter ID = new SqlParameter("@ID", SqlDbType.UniqueIdentifier, 50);
                ID.Direction = ParameterDirection.Input;
                ID.Value = instance.ID;
                SqlParameter Code = new SqlParameter("@Code", SqlDbType.Char, 15);
                Code.Direction = ParameterDirection.Input;
                Code.Value = instance.Code;
                SqlParameter OrderProductID = new SqlParameter("@OrderProductID", SqlDbType.UniqueIdentifier, 50);
                OrderProductID.Direction = ParameterDirection.Input;
                OrderProductID.Value = instance.OrderProductID;
                SqlParameter ProductLayoutID = new SqlParameter("@ProductLayoutID", SqlDbType.UniqueIdentifier, 50);
                ProductLayoutID.Direction = ParameterDirection.Input;
                ProductLayoutID.Value = instance.ProductLayoutID;
                SqlParameter NegotiateTeach = new SqlParameter("@NegotiateTeach", SqlDbType.UniqueIdentifier, 50);
                NegotiateTeach.Direction = ParameterDirection.Input;
                NegotiateTeach.Value = instance.NegotiateTeach;
                SqlParameter ClassServer = new SqlParameter("@ClassServer", SqlDbType.UniqueIdentifier, 50);
                ClassServer.Direction = ParameterDirection.Input;
                ClassServer.Value = instance.ClassServer;
                SqlParameter ClassFrontServer = new SqlParameter("@ClassFrontServer", SqlDbType.UniqueIdentifier, 50);
                ClassFrontServer.Direction = ParameterDirection.Input;
                ClassFrontServer.Value = instance.ClassFrontServer;
                SqlParameter DliverState = new SqlParameter("@DliverState", SqlDbType.UniqueIdentifier, 50);
                DliverState.Direction = ParameterDirection.Input;
                DliverState.Value = instance.DliverState;
                SqlParameter AddUser = new SqlParameter("@AddUser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = instance.AddUser;
                SqlParameter AddTime = new SqlParameter("@AddTime", SqlDbType.DateTime, 50);
                AddTime.Direction = ParameterDirection.Input;
                AddTime.Value = instance.AddTime;
                SqlParameter StudentList = new SqlParameter("@StudentList", SqlDbType.NVarChar, 4000);
                StudentList.Direction = ParameterDirection.Input;
                StudentList.Value = instance.StudentList;

                SqlParameter WorkFlowId = new SqlParameter("@WorkFlowId", SqlDbType.NVarChar, 50);
                WorkFlowId.Direction = ParameterDirection.Input;
                WorkFlowId.Value = instance.WorkFlowId;
                SqlParameter WorkTaskId = new SqlParameter("@WorkTaskId", SqlDbType.NVarChar, 50);
                WorkTaskId.Direction = ParameterDirection.Input;
                WorkTaskId.Value = instance.WorkTaskId;
                SqlParameter WorkFlowInsId = new SqlParameter("@WorkFlowInsId", SqlDbType.NVarChar, 50);
                WorkFlowInsId.Direction = ParameterDirection.Input;
                WorkFlowInsId.Value = instance.WorkFlowInsId;
                SqlParameter WorkTaskInsId = new SqlParameter("@WorkTaskInsId", SqlDbType.NVarChar, 50);
                WorkTaskInsId.Direction = ParameterDirection.Input;
                WorkTaskInsId.Value = instance.WorkTaskInsId;


                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;

                _Parameters = new IDataParameter[] { ID,Code,OrderProductID,ProductLayoutID,NegotiateTeach,
					                        ClassServer,ClassFrontServer,DliverState,AddUser,AddTime, StudentList, 
                                            WorkFlowId,WorkTaskId,WorkFlowInsId,WorkTaskInsId,ReturnValue};
                string strSql = db.RunProcedureReturnString("sp_AddCrmDeliverMajor", _Parameters, out iResult);

                if (strSql == "1")
                {
                    string userId = this.User.LoginName;
                    CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                    string msgClaim = client.TaskClaim(this.User.LoginName, strJson);
                    string msgRun = client.Start(userId, WorkFlowId.Value.ToString(), WorkTaskId.Value.ToString(),
                         WorkFlowInsId.Value.ToString(), WorkTaskInsId.Value.ToString(), client.GetWorkFlowNO(), "提交", "3", "大课交付申请单", false);
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("保存数据失败!");
                }
                /*if (strSql == "1")
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("保存数据失败!");
                }*/
            }
            catch
            {
                HttpContext.Current.Response.Write("数据异常!保存失败!");
            }
        }
        private void InsertDeliverMajorProject(string strEntity, string strJson)
        { 
            int iResult = 0;
            IDataParameter[] _Parameters = new IDataParameter[] { };
            DbSql db = new DbSql();
            try
            {
                CrmDeliverMajorProject instance = (CrmDeliverMajorProject)Globals.JSonToObject<CrmDeliverMajorProject>(strJson);
                Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);

                SqlParameter Code = new SqlParameter("@Code", SqlDbType.Char, 15);
                Code.Direction = ParameterDirection.Input;
                Code.Value = instance.Code;
                SqlParameter ProductID = new SqlParameter("@ProductID", SqlDbType.UniqueIdentifier, 50);
                ProductID.Direction = ParameterDirection.Input;
                ProductID.Value = new Guid(instance.exp1);
                SqlParameter OrderID = new SqlParameter("@OrderID", SqlDbType.UniqueIdentifier, 50);
                OrderID.Direction = ParameterDirection.Input;
                OrderID.Value =new Guid(instance.exp2);
                SqlParameter ClassFrontServer = new SqlParameter("@ClassFrontServer", SqlDbType.UniqueIdentifier, 50);
                ClassFrontServer.Direction = ParameterDirection.Input;
                ClassFrontServer.Value = instance.ClassFrontServer;
       
                SqlParameter AddUser = new SqlParameter("@AddUser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = instance.AddUser;
                SqlParameter AddTime = new SqlParameter("@AddTime", SqlDbType.DateTime, 50);
                AddTime.Direction = ParameterDirection.Input;
                AddTime.Value = instance.AddTime;
                SqlParameter WorkFlowId = new SqlParameter("@WorkFlowId", SqlDbType.NVarChar, 50);
                WorkFlowId.Direction = ParameterDirection.Input;
                WorkFlowId.Value = instance.WorkFlowId;
                SqlParameter WorkTaskId = new SqlParameter("@WorkTaskId", SqlDbType.NVarChar, 50);
                WorkTaskId.Direction = ParameterDirection.Input;
                WorkTaskId.Value = instance.WorkTaskId;
                SqlParameter WorkFlowInsId = new SqlParameter("@WorkFlowInsId", SqlDbType.NVarChar, 50);
                WorkFlowInsId.Direction = ParameterDirection.Input;
                WorkFlowInsId.Value = instance.WorkFlowInsId;
                SqlParameter WorkTaskInsId = new SqlParameter("@WorkTaskInsId", SqlDbType.NVarChar, 50);
                WorkTaskInsId.Direction = ParameterDirection.Input;
                WorkTaskInsId.Value = instance.WorkTaskInsId;
                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;

                _Parameters = new IDataParameter[] { Code,ProductID,OrderID,ClassFrontServer,AddUser,AddTime, 
                                            WorkFlowId,WorkTaskId,WorkFlowInsId,WorkTaskInsId, ReturnValue};
                string strSql = db.RunProcedureReturnString("sp_AddCrmDeliverMajorProject", _Parameters, out iResult);
                if (strSql == "1")
                {
                    string userId = this.User.LoginName;
                    CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                    string msg1 = client.Start(userId, WorkFlowId.Value.ToString(), WorkTaskId.Value.ToString(),
                         WorkFlowInsId.Value.ToString(), WorkTaskInsId.Value.ToString(), client.GetWorkFlowNO(), "提交", "3", "项目交付申请单", false);
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("保存数据失败!");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("保存数据失败!");
            }
        }
        /// <summary>
        /// 保存联系人信息
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void InsertCrmLinkMan(string strEntity, string strJson)
        {
            try
            {
                CrmLinkMan instance = (CrmLinkMan)Globals.JSonToObject<CrmLinkMan>(strJson);
                Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);

                string strSqls = string.Format("Exec sp_AddCrmLinkMan '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}'",
                                                    instance.ID, instance.Code, instance.Caption, instance.CustomId,
                                                    instance.TypeID, instance.Sex, instance.Position,
                                                    instance.DeptName, instance.MobileTel, instance.Email,
                                                    instance.AddUser, instance.AddTime);
                int iResults = bll.RunSqlCommand(strSqls);
                if (iResults > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 保存行销中心记录
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void InsertCrmActivity(string strEntity, string strJson)
        {
            try
            {
                CrmActivity instance = (CrmActivity)Globals.JSonToObject<CrmActivity>(strJson);
                Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);

                string strSqls = "";
                if (strEntity == "CrmActivity") {
                    strSqls = string.Format("Exec sp_AddCrmActivity '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}'",
                                                instance.ID, iSun.BLL.IDMaker.GetSequenceStr("CUS003"),
                                                instance.Caption, instance.CustomId, instance.TypeId,
                                                instance.LinkManID, instance.PlanStartDate, instance.PlanEndDate,
                                                instance.Contents, instance.Explain, instance.AddUser,
                                                instance.AddTime, "", "");
                }
                else if (strEntity == "CrmActivityInfo")
                {
                    strSqls = string.Format("Exec sp_AddCrmActivity '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}'",
                                                instance.ID, iSun.BLL.IDMaker.GetSequenceStr("CUS003"),
                                                instance.Caption, instance.CustomId, instance.TypeId,
                                                instance.LinkManID, instance.PlanStartDate, instance.PlanEndDate,
                                                instance.Contents, instance.Explain, instance.AddUser,
                                                instance.AddTime, instance.AnticipeResult, instance.Result);
                }
                int iResults = bll.RunSqlCommand(strSqls);
                if (iResults > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 客户修改保存修改日志
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void InsertCrmCustomerOperator(string strEntity, string strJson)
        {
            try
            {
                string strCustomerId = this.GetStringFromQueryString("id",""); //客户ID
                string strSqls = string.Format("Exec sp_AddCrmCustomerOperator '{0}','{1}','{2}','{3}','{4}','{5}'",
                                                    this.UserId, new Guid(strCustomerId), strJson,
                                                    "客户修改日志记录", this.UserId, DateTime.Now.ToString());
                int iResults = bll.RunSqlCommand(strSqls);
                if (iResults > 0)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
    }
}